package com.k.demo.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.k.demo.entity.CustomerUser;
import com.k.demo.service.CustomerUserService;
import com.k.demo.util.face.FaceUtil;

@RestController
@RequestMapping("/user")
public class FaceController{
	
	@Autowired
	private CustomerUserService customerUserService;
	
	@Value("${lc.upload.path}")
	private String uploadPath;
	
	@RequestMapping("/faceRegister")
	public Object faceRegister(@RequestParam("file") MultipartFile file, HttpSession session){
		
		Map<String, Object> map = new HashMap<String,Object>();
		
		CustomerUser user=(CustomerUser) session.getAttribute("loginUser");
		
		map.put("message", false);
		
		if (user == null) {
			map.put("message", false);
			map.put("tip", "请先登录");
		}else {
			String path = user.getUser_id()+user.getUser_name()+".jpg";
			String filePath = uploadPath+"/"+path;
			try {
				File f = new File(filePath);
				file.transferTo(f);
			} catch (Exception e) {
				map.put("message", false);
				// TODO: handle exception
			}
			user.setUser_picture(filePath);
			boolean b = customerUserService.updateCustomerUser(user);
			map.put("message", b);
		}
		
		return map;
	}
	
	
	@RequestMapping("/faceLogin")
	public Object faceLogin(@RequestParam("file") MultipartFile file, HttpSession session) throws IOException{
		List<CustomerUser> list = customerUserService.getAll();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("isLogin", false);
		InputStream in = null;
		byte[] image1 = null;
		for (CustomerUser c : list) {
			if (c.getUser_picture()!=null && (!c.getUser_picture().trim().equals(""))) {
				try {
					in = new FileInputStream(c.getUser_picture());
					image1 = new byte[in.available()];
					in.read(image1);
					String base1 = FaceUtil.encodeBase64(image1);
					String base = FaceUtil.encodeBase64(file.getBytes());
					boolean loginBool = FaceUtil.faceContrast(base, base1);
					if (loginBool) {
						map.put("isLogin", true);
						session.setAttribute("loginUser", c);
						in.close();
						break;
					}
				} catch (FileNotFoundException e) {
					// TODO: handle exception
					System.out.println("文件不存在");
				}finally {
					
				}
				
			}
		}
		return map;
	}
}
